﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sami_SMS_CRM_Business;
using System.IO;

namespace Sami_SMS_CRM_UI
{
    public partial class crm_subscriber_import : BasePage
    {
        SubscriberImportRepository repository = new SubscriberImportRepository();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!AllowManageAdvertisment())
            {
                RedirectToPage(AccessDeniedURL);
            }
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindDataTable();
            pagingtop.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCombo();
                PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
                pagingtop.CurrentPage = 1;
                pagingtop.PageSize = PageSize;
                pagingtop.PageDisplay = PageDisPlay;
                pagingbottom.CurrentPage = 1;
                pagingbottom.PageSize = PageSize;
                pagingbottom.PageDisplay = PageDisPlay;
                BindDataTable();
            }
        }

        private void BindDataTable()
        {
            try
            {
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRecord = 0;
                int? collection_id = string.IsNullOrEmpty(ddlCollection.SelectedValue) ?
                                        (int?)null : int.Parse(ddlCollection.SelectedValue);
                string subscriber = txtSubscriber.Text.Trim();
                int? service_id = null;
                switch (ddlService3.SelectedValue)
                {
                    case "null":
                        service_id = null;
                        break;
                    case "":
                        service_id = -1;
                        break;
                    default:
                        service_id = int.Parse(ddlService3.SelectedValue);
                        break;
                }

                rptTable.DataSource = repository.GetAll(subscriber, collection_id, service_id, currentPage, pageSize, ref totalRecord);
                rptTable.DataBind();

                pagingtop.TotalRecord = totalRecord;
                pagingtop.Visible = pagingtop.TotalPage > 1;
                pagingbottom.TotalRecord = totalRecord;
                pagingbottom.Visible = pagingtop.TotalPage > 1;
                ltrTotalRow.Text = totalRecord.ToString();
            }
            catch (Exception e)
            {
                ShowMessageBox(e.Message);
            }
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            pagingtop.PageSize = pagingbottom.PageSize = int.Parse((sender as DropDownList).SelectedValue);
            BindDataTable();
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDataTable();
        }

        protected void btnSearching_Click(object sender, EventArgs e)
        {
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            BindDataTable();
        }

        protected void rptTable_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "Edited":
                        hdfAction.Value = "Edit";
                        hdfId.Value = e.CommandArgument.ToString();
                        SetDataDialog(e.CommandArgument);
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "OpenDialog('dialog-form1');", true);
                        break;
                    case "Deleted":
                        repository.DeleteByID(e.CommandArgument);
                        BindDataTable();
                        break;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void LoadCombo()
        {
            ddlCollection.DataSource = ddlCollection2.DataSource = ddlCollection3.DataSource = new CollectionRepository().GetAll();
            ddlCollection.DataValueField = ddlCollection2.DataValueField = ddlCollection3.DataValueField = "collection_id";
            ddlCollection.DataTextField = ddlCollection2.DataTextField = ddlCollection3.DataTextField = "collection_name";
            ddlCollection.DataBind();
            ddlCollection2.DataBind();
            ddlCollection3.DataBind();
            ddlCollection.Items.Insert(0, new ListItem("-----------", ""));

            if (ddlSenderName.Items.Count == 0)
            {
                foreach (var item in new SenderNameRepository().GetAll())
                {
                    ddlSenderName.Items.Add(new ListItem(item.sender_name, item.sender_name));
                }
            }

            ddlService.DataSource = ddlService2.DataSource = ddlService3.DataSource = new ServiceRepository().GetAll();
            ddlService.DataValueField = ddlService2.DataValueField = ddlService3.DataValueField = "sevice_id";
            ddlService.DataTextField = ddlService2.DataTextField = ddlService3.DataTextField = "service_name";
            ddlService.DataBind();
            ddlService2.DataBind();
            ddlService3.DataBind();
            ddlService.Items.Insert(0, new ListItem("-----------", ""));
            ddlService2.Items.Insert(0, new ListItem("-----------", ""));
            ddlService3.Items.Insert(0, new ListItem("", "null"));
            ddlService3.Items.Insert(0, new ListItem("-----------", ""));
        }

        private void SetDataDialog(object id)
        {
            var entity = repository.GetByID(id);
            if (entity != null)
            {
                txtSubs.Text = entity.subscriber;
                ddlSenderName.SelectedValue = entity.vasp_num;
                ddlCollection2.SelectedValue = entity.collection_id.ToString();
                txtOperatorId.Text = entity.operator_id.ToString();
                txtGatewayId.Text = entity.gateway_id.ToString();
                if (entity.service_id != null)
                    ddlService.SelectedValue = entity.service_id.ToString();
                else
                    ddlService.SelectedIndex = 0;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                switch (hdfAction.Value)
                {
                    case "Edit":
                        var entity = repository.GetByID(hdfId.Value);
                        if (entity != null)
                        {
                            entity.subscriber = txtSubs.Text;
                            entity.vasp_num = ddlSenderName.SelectedValue;
                            entity.collection_id = int.Parse(ddlCollection2.SelectedValue);
                            entity.operator_id = txtOperatorId.Text == "" ? (int?)null : int.Parse(txtOperatorId.Text);
                            entity.gateway_id = txtGatewayId.Text;
                            entity.service_id = ddlService.SelectedValue == "" ? (int?)null : int.Parse(ddlService.SelectedValue);
                            repository.SaveChange();
                        }
                        break;
                    case "AddNew":
                        repository.Insert(new Sami_SMS_CRM_Business.crm_subscriber_import()
                        {
                            guid_key = Guid.NewGuid(),
                            subscriber = txtSubs.Text,
                            vasp_num = ddlSenderName.SelectedValue,
                            operator_id = txtOperatorId.Text == "" ? (int?)null : int.Parse(txtOperatorId.Text),
                            gateway_id = txtGatewayId.Text,
                            service_id = ddlService.SelectedValue == "" ? (int?)null : int.Parse(ddlService.SelectedValue)
                        });
                        break;
                }
                BindDataTable();
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message);
            }
        }

        private void CheckFullInfo()
        {
            if (txtSubs.Text.Trim() == "")
                throw new Exception("subscriber not allow null");
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string fileName = string.Empty;
            string filePath = string.Empty;
            try
            {
                if (!ful.HasFile)
                {
                    RegisterStartUpScrip("RegisterDialog(); OpenDialog('dialog-form2'); alert('Please choose a Execel file to import data');");
                    return;
                }
                string excelContentType = "application/vnd.ms-excel";
                string excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                if (ful.PostedFile.ContentType != excel2010ContentType
                    && ful.PostedFile.ContentType != excelContentType)
                {
                    RegisterStartUpScrip("RegisterDialog(); OpenDialog('dialog-form2'); alert('Please choose a Execel file to import data');");
                    return;
                }
                if (ful.PostedFile.ContentLength > (1024 * 1024 * 200))
                {
                    RegisterStartUpScrip("RegisterDialog(); OpenDialog('dialog-form2'); alert('File size must be less than 200MB');");
                }
                fileName = Guid.NewGuid() + ful.FileName;
                filePath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                ful.SaveAs(filePath);
                //Insert dữ liệu
                SubscriberImportRepository.BulkInsert(filePath, ddlCollection3.SelectedValue, ddlService2.SelectedValue);
                BindDataTable();
            }
            catch (Exception ex)
            {
                RegisterStartUpScrip("RegisterDialog(); OpenDialog('dialog-form2'); alert(\"" + ex.Message.Replace("\"", "'").Replace(Environment.NewLine, "\\n") + "\");");
            }
            finally
            {
                DeleteFile(filePath);
                RegisterStartUpScrip("RegisterDialog(); OpenDialog('dialog-form2');");
            }
        }

        private void DeleteFile(string filepath)
        {
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
        }

        protected void btnDeleteAll_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                int count = 0;
                foreach (GridViewRow row in rptTable.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        if ((row.FindControl("chkItem") as CheckBox).Checked)
                        {
                            count++;
                            Guid guid_key = Guid.Parse((row.FindControl("hdfItem") as HiddenField).Value);
                            repository.DeleteByID(guid_key);
                        }
                    }
                }
                if (count > 0) BindDataTable();
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message);
            }

        }

        protected void ibtnDownLoad_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(Server.MapPath(@"~/App_Data/Mau_file_up_load.xlsx"));
                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "text/plain";
                Response.Flush();
                Response.TransmitFile(file.FullName);
                Response.End();
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message);
            }
        }
    }
}